package com.opensso.core.tools;

import com.opensso.core.entity.BeanRet;
import com.opensso.core.enums.SessionEnum;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Created by lixin on 2018/8/7.
 */
@Slf4j
public enum HttpTools {
    Instance,;


    /**
     * post 方式请求后端接口
     *
     * @param url api 地址
     * @return SSOResponse
     */
    public BeanRet get(String url) {
        Request request = new Request.Builder()
                .url(url)
                .build();
        return this.http(request);
    }


    /**
     * post 方式请求业务系统的注销功能
     *
     * @param url   api 地址
     * @param token token
     * @return BeanRet
     */
    public BeanRet invalidate(String url, String token) {
        RequestBody formBody = new FormBody.Builder()
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .addHeader("accept", "application/json")
                .addHeader(SessionEnum.Authorization.name(), token)
                .build();
        return this.http(request);
    }

    /**
     * okhttp的网络请求
     *
     * @param request 请求对象
     * @return SSOResponse
     */
    private BeanRet http(Request request) {
        OkHttpClient client = new OkHttpClient.Builder().writeTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS).connectTimeout(15, TimeUnit.SECONDS)
                .addInterceptor(new OkhttpLogInterceptor()).build();
        Response response = null;
        BeanRet beanRet = null;
        try {
            log.info(request.toString());
            response = client.newCall(request).execute();
            String jsonResult = response.body().string();
            log.info("SSOResponse << " + jsonResult);
            if (response.isSuccessful()) {
                return BeanRet.create(true, "", (Object) jsonResult);
            }
//            beanRet = JSON.parseObject(jsonResult, BeanRet.class);
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.toString());
            return BeanRet.create(false, e.toString());
        }
        if (beanRet == null) {
            beanRet = BeanRet.create();
        }
        return beanRet;
    }
}
